package com.betty.cscams.task;

import com.betty.cscams.entity.PsyScore;
import com.betty.cscams.entity.Warning;
import com.betty.cscams.service.PsyScoreService;
import com.betty.cscams.service.WarningService;
import com.betty.cscams.service.BusTermService;
import com.betty.cscams.entity.BusTerm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * ---------------------------
 *  智能预警定时任务(WarningTask)         
 * ---------------------------
 */
@Component
public class WarningTask {
    
    private static final Logger logger = LoggerFactory.getLogger(WarningTask.class);
    
    @Autowired
    private PsyScoreService psyScoreService;
    
    @Autowired
    private WarningService warningService;
    
    @Autowired
    private BusTermService busTermService;
    
    /**
     * 每10分钟执行一次，检查心理测评低分学生并生成预警
     */
    @Scheduled(fixedRate = 600000)
    public void checkLowPsyScores() {
        logger.info("开始执行心理测评低分预警检查任务");
        
        try {
            // 获取当前学期
            BusTerm currentTerm = busTermService.findCurrentTerm();
            if (currentTerm == null) {
                logger.info("当前没有进行中的学期，跳过预警检查");
                return;
            }
            
            // 查询心理测评低分学生
            List<PsyScore> lowScores = psyScoreService.findLowScores(currentTerm.getId(), 60);
            
            int warningCount = 0;
            for (PsyScore score : lowScores) {
                // 检查是否已有预警
                Warning existWarning = warningService.findPsyWarningByStudentAndTerm(
                    score.getStudentNum(), currentTerm.getId());
                
                if (existWarning == null) {
                    // 创建预警
                    boolean success = warningService.createPsyWarning(
                        score.getStudentNum(), currentTerm.getId(), score.getTotalScore().intValue());
                    
                    if (success) {
                        warningCount++;
                    }
                }
            }
            
            logger.info("心理测评低分预警检查完成，新增预警数量: {}", warningCount);
        } catch (Exception e) {
            logger.error("执行心理测评低分预警检查任务出错", e);
        }
    }
} 